home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / Caml Light 0.61 / Binaries / examples / basics / wc.ml < prev   
Encoding:
Text File  |  1993-09-24  |  1.3 KB  |  60 lines  |  [TEXT/ttxt]

  1. (* Counts characters, lines and words in one or several files. *)
  2.  
  3. let chars = ref 0
  4. and words = ref 0
  5. and lines = ref 0
  6. ;;
  7.  
  8. type state = Inside_word | Outside_word;;
  9.  
  10. let count_channel in_channel =
  11.   let rec count status =
  12.     let c = input_char in_channel in
  13.     incr chars;
  14.     match c with
  15.       `\n` ->
  16.         incr lines; count Outside_word
  17.     | ` ` | `\t` ->
  18.         count Outside_word
  19.     | _ ->
  20.         if status = Outside_word then begin incr words; () end;
  21.         count Inside_word
  22.   in
  23.     try
  24.       count Outside_word
  25.     with End_of_file ->
  26.       ()
  27. ;;
  28.  
  29. let count_file name =
  30.   let ic = open_in name in
  31.   count_channel ic;
  32.   close_in ic
  33. ;;
  34.  
  35. let count name =
  36.   count_file name;
  37.   print_int !chars; print_string " characters, ";
  38.   print_int !words; print_string " words, ";
  39.   print_int !lines; print_string " lines";
  40.   print_newline()
  41. ;;
  42.  
  43. if sys__interactive then () else
  44. try
  45.   if vect_length sys__command_line <= 1 then
  46.     count_channel std_in                (* No command-line arguments *)
  47.   else
  48.     for i = 1 to vect_length sys__command_line - 1 do
  49.       count_file  sys__command_line.(i)
  50.     done;
  51.   print_int !chars; print_string " characters, ";
  52.   print_int !words; print_string " words, ";
  53.   print_int !lines; print_string " lines";
  54.   print_newline()
  55. with sys__Sys_error s ->
  56.   print_string "I/O error: ";
  57.   print_string s;
  58.   print_newline()
  59. ;;
  60.